import { useLayoutEffect, useMemo, useRef } from "react";
import { ResourceList } from "../../Component/ResourceList";
import { useDelete } from "../../hooks/useDelete";
import { LibAppView } from "@/lib";
import { AdminRight, useAdminRight } from "../../data/AdminPageAuth";
import { Button } from "antd";
import { FormattedMessage } from "react-intl";
import { PlusOutlined } from "@ant-design/icons";
import ResourceStatus from "../../Component/ResourceStatus";
import { Modal, Input } from "antd";

interface IShowConfig {
    title: string|React.ReactNode;
    content: string|React.ReactNode;
    okText?: string;
    cancelText?: string;
    showConfirm?: boolean;
}
const showConfirm = (opt: IShowConfig) => {
    return new Promise((resolve, reject) => {
        if(opt.showConfirm) {
            Modal.confirm({
                title: opt.title,
                "content": <>{opt.content}</>,
                okText: opt.okText,
                cancelText: opt.cancelText,
                onOk: () => resolve(true),
                onCancel: () => reject(false)
            });
        } else {
            resolve(true);
        }
    });
};

const TextArea = Input.TextArea;

const VenueRouteList = () => {
    const listRef = useRef<any>();
    const microApp = LibAppView.useMicroApp();
    const deleteAction = useDelete({
        endPoint: "venue.venueRouteUpdateStatus",
        cancelEndPoint: "venue.venueRouteUpdateStatus",
        updateEndPoint: "venue.venueRouteUpdateStatus",
        data: {},
        listRef
    });
    const adminApproveRight = useAdminRight("approver");
    const columns = useMemo(() => ([
        {
            title: "研学线路名称",
            dataIndex: "title",
            minWidth: 200
        }, {
            title: "所属地区",
            dataIndex: "location",
            width: 240,
        }, {
            title: "咨询预约方式",
            dataIndex: "contactors",
            width: 120
        },{
            title: "研学时长",
            dataIndex: "duration",
            width: 120
        }, {
            title: "审批拒绝原因",
            dataIndex: "approveMsg",
            width: 200
        }, {
            title: "状态",
            dataIndex: "status",
            width: 100,
            render: (status: number) => {
                return (<>
                    <ResourceStatus status={status} />
                </>);
            }
        }, {
            title: "操作",
            dataIndex: "id",
            width: 230,
            render: (id: string, data: any) => {
                
                const deleteProps = data.status===0 && data.owner ? {} : { disabled: true };
                const approveProps = data.status===2 && adminApproveRight ? {} : { disabled: true };
                const cancelProps = ([1,2].includes(data.status)) && (adminApproveRight || data.owner) ? {} : { disabled: true };
              
                return (<>
                    <Button type="primary" size="small" onClick={() => {
                        microApp.startJourney("editScienceVenueEdit", { state: { ...data } })
                    }}>{ data.status == 0 ? "编辑" : "查看" }</Button>
                    <AdminRight authRight={"editable"}>
                        <Button type="dashed" size="small" {...deleteProps} onClick={() => {
                            deleteAction.delete({...data, status: -1 })
                        }}>删除</Button>
                    </AdminRight>
                    <Button type="default" size="small"
                        {...approveProps}
                        onClick={() => {
                            deleteAction.update({ ...data }, {
                                status: 1,
                                approveMsg: ""
                            });
                        }}
                    >通过</Button>
                    <Button
                        type="default"
                        size="small"
                        {...cancelProps}
                        onClick={async() => {
                            const tmpState = { value: "" };
                            const accept = await showConfirm({
                                title: "拒绝通过审核",
                                content: (<>
                                    <span>审核不通过，请填写拒绝理由</span>
                                    <TextArea placeholder="请输入理由，字数不超过200字。" onChange={(e) => {
                                        tmpState.value = e.target.value;
                                    }}/>
                                </>),
                                showConfirm: data.status == 2 && !data.owner
                            });
                            accept && deleteAction.update({ ...data }, { status: 0, approveMsg: tmpState.value })
                        }}
                    >{ data.owner || data.status == 1 ? "撤销" : "拒绝"}</Button>
                </>);
            }
        }
    ]), [adminApproveRight]);
    const searchFields = useMemo<Admin.IAdvancedField[]>(() => ([{
            label: "研学路线",
            name: "title",
            type: "Input"
        }]), []);
     useLayoutEffect(() => {
        microApp.registeJourney({
            name: "editScienceVenueEdit",
            title: "Edit category",
            stepJourney: true,
            isTempJourney: true,
            steps: [{
                isMemoryPage: true,
                page: "admin.venueRouteEdit"
            }]
        });
    },[]);
    return (
        <ResourceList
            refApi={listRef}
            tableColumns={columns}
            searchFields={searchFields}
            tableWidth={800}
            listEndPoint={{
                endPoint: "venue.venueRouteList",
                formatResponse: (resp: any) => {
                    const listData: any[] = resp.data || [];
                    return listData.map((item: any) => {
                        // const categoryData = categoryList.find((item2: any) => item2.value === item.type);
                        return {
                            ...item,
                            // typeTitle: categoryData?.label || "未知",
                        };
                    });
                }
            }}
            Operators={() => {
                return (<AdminRight authRight="editable" mode="disabled">
                    <Button type="primary" onClick={() => {
                        microApp.startJourney("editScienceVenueEdit");
                    }}>
                        <PlusOutlined />
                        <span><FormattedMessage id="admin.pages.operate.add" /></span>
                    </Button>
                </AdminRight>);
            }}
        />
    );
};


export default VenueRouteList;
